package com.xuecheng.web.interceptor;

/*
* 自定义拦截器
* */

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

public class AuthInfoInterceptor implements HandlerInterceptor {

    //进入controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的payload
        String payload = request.getHeader("payload");
        if (StringUtils.isEmpty(payload)) {
            return true;
        }
        //2.转换编码
        String json = URLDecoder.decode(payload, "UTF-8");
        //3.转换成AuthInfo对象
        AuthInfo info = JSON.parseObject(json, AuthInfo.class);
        //4.存入ThreadLocal
        AuthInfoHolder.setAuthInfo(info);
        //true:向后执行controller方法
        return true;
    }

    //响应结束之前
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
